const Base = require('./base.js');
const moment = require('moment');
const xxphoto='https://www.coastalinfo.cn/coastalShop/static/temp/xxhg.jpg';
//抽奖管理
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id asc';
        const goodsname = this.get('name') || '';
        const state = this.get('state') || '';
        const begin = this.get('begin') || '';
        const end = this.get('end') || '';
        let seachdata = { id:['>',0]}, timesearch = {};
        if (goodsname) {
            seachdata['name'] = ['like', `%${goodsname}%`];
        }
        if(state||state===0){//是否停止
            seachdata['status'] = state;
        }
        if(begin){
            seachdata['begin_time'] = ['egt',begin];
        }
        if(end){
            seachdata['end_time'] = ['elt',end];
        }

        const model = this.model('lottery');
        const data = await model.where(seachdata)
        .order([sortField]).page(page, size).countSelect();
         for(const item of data.data){
            item.statusText= this.getStatusText(item.status);
            item.usersum = await this.model('lottery_user').where({lottery_id:item.id}).count('distinct user_id');
            item.usernumber = await this.model('lottery_user').where({lottery_id:item.id}).count('id');
            item.userprizesum = await this.model('lottery_user').where({lottery_id:item.id,lottery_row_id:['>',0]}).count('distinct user_id');
            item.userprizenumber = await this.model('lottery_user').where({lottery_id:item.id,lottery_row_id:['>',0]}).count('id');
        }
        return this.success(data);
    }


     /**
     * 选择商品
     * @return {Promise} []
     */
    async selectGoodsAction() {
        const page = this.post('page') || 1;
        const size = this.post('size') || 10;
        const sortField = this.post('sortfield') || 'gi.sort_order,gi.order_time desc';
        const goodsname = this.post('goodsname') || '';
        const category_id = this.post('category_id') || '';
        const goods_ids = this.post('goods_ids') || [];
        const state = this.post('state') || '';
        let seachdata = { 'gi.is_delete': 0}, timesearch = {};
        if (category_id) {
            seachdata['hiolabs_goods.category_id'] = category_id;
        }
        if (goodsname) {
            seachdata['hiolabs_goods.name'] = ['like', `%${goodsname}%`];
        }
        if (state || state === 0) {
            seachdata['gi.is_delete'] = state;
        }
        if (goods_ids&&goods_ids.length>0) {
            seachdata['gi.goods_id'] = ['NOT IN', goods_ids];
        }

        const model = this.model('goods');
        const total  = await model
        .join({ table: 'goods_integral', join: 'left', as: 'gi', on: ['id', 'gi.goods_id'] })
        .where(seachdata)
        .count('distinct hiolabs_goods.id');
        const data = await model
            .join({ table: 'goods_integral', join: 'left', as: 'gi', on: ['id', 'gi.goods_id'] })
            .where(seachdata)
            // .group('hiolabs_goods.id,hiolabs_goods.name')
            .field('distinct hiolabs_goods.id as goods_id,hiolabs_goods.name,hiolabs_goods.list_pic_url')
            .order([sortField]).page(page, size).countSelect(total);
        return this.success(data);
    }

    async saveAction() {
        const model = this.model('lottery');
        const rmodel = this.model('lottery_row');
        const tmodel = this.model('lottery_table');
        const values = this.post();
        let id = this.post('id')||0;
        let prize = this.post('prize')||[];
        if(values['times']<1){
            return this.fail(400,'每人抽奖上限应大于0');
        }
        if(prize.length<4||prize.length>8){
            return this.fail(400,'奖品的数量需在4到8个以内（包含）');
        }
        if (id>0) {
            return this.fail(400,'添加请不要加入id参数');
        } else {
            values['id']=0;
            values['add_time'] = Math.floor((new Date()).getTime() / 1000);
            id = await model.add(values);
            for(const pr of prize){
                pr.add_time=values['add_time'];
                pr.lottery_id=id;
                let rid = await rmodel.add(pr);
                pr.lottery_row_id=rid;
            }
            let count = 8-prize.length;
            switch(count){
                case 1:
                    prize.splice(4,0,{
                        lottery_id: id,
                        lottery_row_id: 0,
                        name:'谢谢参与',
                        pic: xxphoto,
                        add_time: values['add_time']
                    });
                    break;
                case 2:
                    for(let i=1;i<count+1;i++){
                        prize.splice(i*2,0,{
                            lottery_id: id,
                            lottery_row_id: 0,
                            name:'谢谢参与',
                            pic: xxphoto,
                            add_time: values['add_time']
                        });    
                    }
                    break;
                case 3:
                    for(let i=1;i<count+1;i++){
                        prize.splice(i*2,0,{
                            lottery_id: id,
                            lottery_row_id: 0,
                            name:'谢谢参与',
                            pic: xxphoto,
                            add_time: values['add_time']
                        });    
                    }
                    break;
                case 4:
                    for(let i=1;i<count+1;i++){
                        prize.splice(i*2-1,0,{
                            lottery_id: id,
                            lottery_row_id: 0,
                            name:'谢谢参与',
                            pic: xxphoto,
                            add_time: values['add_time']
                        });    
                    }
                    break;
                default:

            }
            for(let j=0;j<prize.length;j++){
                prize[j].number=j;
            }
            await tmodel.addMany(prize);
            values['id'] = id;
        }
        return this.success(values);
    }
    async updateAction() {
        const model = this.model('lottery');
        const rmodel = this.model('lottery_row');
        const tmodel = this.model('lottery_table');
        const values = this.post();
        let id = this.post('id')||0;
        let prize = this.post('prize')||[];
        const record = await this.model('lottery_user').where({lottery_id:id}).find();
        if(!think.isEmpty(record)){
            return this.fail(400,'已有中奖记录的数据不能修改');
        }
        if(prize.length<4||prize.length>8){
            return this.fail(400,'奖品的数量需在4到8个以内（包含）');
        }
        let data;
        if (id<0) {
            return this.fail(400,'缺少id参数');
        } else {
            values['update_time'] = Math.floor((new Date()).getTime() / 1000);
            data = await model.where({id:id}).update(values);
            await rmodel.where({lottery_id:id}).delete();
            await tmodel.where({lottery_id:id}).delete();
            for(const pr of prize){
                pr.id=0;
                pr.add_time=values['update_time'];
                pr.lottery_id=id;
                let rid = await rmodel.add(pr);
                pr.lottery_row_id=rid;
            }
            let count=8-prize.length;
            switch(count){
                case 1:
                    prize.splice(4,0,{
                        lottery_id: id,
                        lottery_row_id: 0,
                        name:'谢谢参与',
                        pic: xxphoto,
                        add_time: values['update_time']
                    });
                    break;
                case 2:
                    for(let i=1;i<count+1;i++){
                        prize.splice(i*2,0,{
                            lottery_id: id,
                            lottery_row_id: 0,
                            name:'谢谢参与',
                            pic: xxphoto,
                            add_time: values['update_time']
                        });    
                    }
                    break;
                case 3:
                    for(let i=1;i<count+1;i++){
                        prize.splice(i*2,0,{
                            lottery_id: id,
                            lottery_row_id: 0,
                            name:'谢谢参与',
                            pic: xxphoto,
                            add_time: values['update_time']
                        });    
                    }
                    break;
                case 4:
                    for(let i=1;i<count+1;i++){
                        prize.splice(i*2-1,0,{
                            lottery_id: id,
                            lottery_row_id: 0,
                            name:'谢谢参与',
                            pic: xxphoto,
                            add_time: values['update_time']
                        });    
                    }
                    break;
                default:

            }
            for(let j=0;j<prize.length;j++){
                prize[j].id=0;
                prize[j].number=j;
            }
            await tmodel.addMany(prize);
        }
        return this.success(values);
    }

    async readAction() {
        const model = this.model('lottery');
        const id = this.get('id');
        const data=await model.where({id: id}).find();
        data.prize=await this.model('lottery_row').where({'lottery_id': id}).select();
        return this.success(data);
    }
     /**
     *开始或终止
     */
    async changeAction() {
        const model = this.model('lottery');
        const values = this.post();
        const id = this.post('id');
        const status = this.post('status');
        const rdata = await model.where({id: id}).find();
        if(rdata.status===3||moment()>moment(rdata.end_time)){
    return this.fail(400,'活动已结束');
        }
        let data = await model.where({id: id}).update({status:status,update_time:Math.floor(new Date().getTime()/1000)});
        return this.success(data);
    }

    /**
     *发放
     */
    async sendAction() {
        const model = this.model('lottery_user');
        // const values = this.post();
        const id = this.post('id')||0;
        // const status = this.post('status');
        const rdata = await model.where({id: id}).find();
        if(rdata.status===0&&rdata.info_time<1){
            return this.fail(400,'需要用户完善资料才能发放');
        }
        let data = await model.where({id: id}).update({status:2,send_time:Math.floor(new Date().getTime()/1000)});
        return this.success(data);
    }
    /**
     * 置顶
     */
    async topAction() {
        const model = this.model('lottery');
        const values = this.post();
        const id = this.post('id');
        const sort_order = this.post('sort_order');
        let data;

        try{
            await model.startTrans();
            data = await model.where({id: id}).update({sort_order:sort_order});
            await model.where({id: ['!=',id]}).update({sort_order:1-sort_order});
            await model.commit();
          }catch(e){
            await model.rollback();
            return this.fail('事务，未知错误');
          }
        return this.success(data);
    }



    async deleteAction() {
        const model = this.model('lottery');
        const rmodel = this.model('lottery_row');
        const tmodel = this.model('lottery_table');
        const id = this.post('id');
        const record = await this.model('lottery_user').where({lottery_id:id}).find();
        if(!think.isEmpty(record)){
    return this.fail(400,'已有中奖记录的数据不能删除');
        }
        let data = await model.where({ id: id }).delete();
        await rmodel.where({lottery_id:id}).delete();
        await tmodel.where({lottery_id:id}).delete();
        return this.success(data);
    }


    /**
     * 中奖统计
     */
    async prizeStaticAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const id = this.get('id') || 0;
        const sortField = this.get('sortfield') || 'hiolabs_lottery_user.add_time';
        const goodsname = this.get('goodsname') || '';
        const goods_id = this.get('goods_id') || 0;
        const begin = this.get('begin') || '';
        const end = this.get('end') || '';
        const status = this.get('status') || '';
        let name = this.get('name') || '';
        const buffer = Buffer.from(name);
        let nickname = buffer.toString('base64');

        let searchData = { 'hiolabs_lottery_user.lottery_row_id':['>',0]}, timesearch = {};
        if(id){
            searchData['hiolabs_lottery_user.lottery_id'] = id;
        }
        if(goods_id){
            searchData['lr.goods_id'] = goods_id;
        }
        if (goodsname) {
            searchData['lr.original_name'] = ['like', `%${goodsname}%`];
        }
        if(status||status==='0'){
            searchData['hiolabs_lottery_user.status'] = status;
        }

        if(name){
            searchData['_complex'] = {
                'ou.nickname':['like', `%${nickname}%`],
                'ou.name':['like', `%${name}%`],
                'ou.mobile':['like', `%${name}%`],
                _logic:'or'
            };
        }

        if (begin || end) {
            if (begin) {
                timesearch['egt'] = parseInt(new Date(begin).getTime()/1000);
            }
            if (end) {
                timesearch['elt'] = parseInt(new Date(end).getTime()/1000);
            }
            searchData['hiolabs_lottery_user.add_time'] = timesearch;
        }

        const model = this.model('lottery_user');
        const data = await model.join({ table: 'lottery_row',  join: 'left', as:'lr', on: ['lottery_row_id', 'id'] })
        .join({ table: 'user',  join: 'left', as:'ou', on: ['hiolabs_lottery_user.user_id', 'id'] }).where(searchData)
        .field('hiolabs_lottery_user.*,ou.nickname,ou.name,ou.mobile,lr.name,lr.original_name')
        .order(sortField).page(page,size).countSelect();
        for(const item of data.data){
            item.nickname = Buffer.from(item.nickname, 'base64').toString();
            item.nowstatus = await this.getnowStatusText(item.status);//现状态
            item.add_time= moment.unix(item.add_time).format('YYYY-MM-DD HH:mm:ss');
        }

        return this.success(data);
    }

    getStatusText(status){
        switch(status){
            case 0:
                return '未开始';
            case 1:
                return '执行中';
            case 2:
                return '中止';
            case 3:
                return '结束';
            default:
                return '未开始';
        }
    }
    getnowStatusText(status){
        switch(status){
            case 0:
                return '未领取';
            case 1:
                return '待发放';
            case 2:
                return '已领取';
            default:
                return '未领取';
        }
    }


};